package com.zhx.threadcoreknowledge.synchromized;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-02 11:09
 * 用途         ： 访问一个类的不同的普通同步方法
 */
public class SynchorizedDifferentMethod7 implements Runnable{
    private static SynchorizedDifferentMethod7 instance=new SynchorizedDifferentMethod7();

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")){
            try {
                method1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            try {
                method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(instance);
        Thread thread2 = new Thread(instance);
        thread1.start();
        thread2.start();

        while (thread1.isAlive() || thread2.isAlive()){

        }

        System.out.println("finashed");
    }

    /**
     * 同一个实例来讲这个方法用的是this作为关键字
     * @throws InterruptedException
     */
    public synchronized void method1() throws InterruptedException {
        System.out.println("我是方法1,我叫:"+Thread.currentThread().getName());
        Thread.sleep(3000);
        System.out.println(Thread.currentThread().getName()+"运行结束了");
    }

    public synchronized void method2() throws InterruptedException {
        System.out.println("我是方法2,我叫:"+Thread.currentThread().getName());
        Thread.sleep(3000);
        System.out.println(Thread.currentThread().getName()+"运行结束了");
    }
}
